/**
* All Rights Reserved , Copyright (C) 2020 , 青岛鼎信通讯股份有限公司
*
* PmAttachmentService
* 项目资料
*
* 修改纪录
* 2020-05-16 版本：1.0 fanzhiming 创建。
* @version 版本：1.0
* @author 作者：fanzhiming
* 创建日期：2020-05-16
*/
package com.topscomm.pm.service.impl;

import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.CboAttachmentTypeEntity;
import com.topscomm.cbo.service.impl.CboAttachmentService;
import com.topscomm.cbo.service.impl.CboAttachmentTypeService;
import com.topscomm.pm.pojo.PmAttachmentEntity;
import com.topscomm.pub.util.*;
import com.topscomm.tap.common.TapSystemConst;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import com.topscomm.pm.service.IPmAttachmentService;
import com.topscomm.pm.service.impl.auto.PmAttachmentServiceAuto;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service(value = "pmAttachmentService")
@Scope(value = "singleton")
public class PmAttachmentService extends PmAttachmentServiceAuto implements IPmAttachmentService {

    @Resource
    private CboAttachmentService cboAttachmentService;
    @Resource
    private CboAttachmentTypeService cboAttachmentTypeService;
    @Resource
    private FastDFSClient fastDFSClient;

    private static List<String> updateFields = new ArrayList<>();

    static {
        updateFields.add("displayname");
        updateFields.add("attachmenttypeid");
        updateFields.add("savepath");
        updateFields.add("filetype");
        updateFields.add("uploaddate");
        updateFields.add("description");
        updateFields.add("filename");
        updateFields.add("pwd");
        updateFields.add("filesize");
    }

    /**
      * @author: shenyouyi
      * @date: 2020/6/16
      * @param
      * @description: 上传文件到服务器
      **/
    @Override
    public Map<String, Object> executeUpload(Map<String, Object> paraMap, File attachFile) {
        Object resultMap = new HashMap();

        try {
            String id = ConvertUtil.convertToString(paraMap.get("id"));
            String attachFileName = ConvertUtil.convertToString(paraMap.get("attachFileFileName"));
            if (StringUtil.isEmpty(attachFileName)) {
                attachFileName = attachFile.getName();
            }

            String description = "";
            if (paraMap.containsKey("description")) {
                description = ConvertUtil.convertToString(paraMap.get("description"));
            }

            CboAttachmentTypeEntity attachmentType = new CboAttachmentTypeEntity();
            if (paraMap.containsKey("attachmentTypeId")) {
                String attachmentTypeId = ConvertUtil.convertToString(paraMap.get("attachmentTypeId"));
                attachmentType = cboAttachmentTypeService.queryById(attachmentTypeId);
            } else if (paraMap.containsKey("sourceType")) {
                attachmentType = cboAttachmentTypeService.queryObjectByWhere("sourceType='" + paraMap.get("sourceType") + "' and enabled=1");
            }


            PmAttachmentEntity entity;
            if (attachmentType.getStoretype().equals(TapSystemConst.TapAttachmentStoreType.FTP)) {
                entity = this.uploadFtp(id, attachFileName, attachmentType, attachFile, description);
                resultMap = entity.convertToMap();
            } else if (attachmentType.getStoretype().equals(TapSystemConst.TapAttachmentStoreType.Database)) {
                entity = this.uploadDatabase(id, attachFileName, attachmentType, attachFile, description);
                resultMap = entity.convertToMap();
            } else if (attachmentType.getStoretype().equals(TapSystemConst.TapAttachmentStoreType.Web)) {
                entity = this.uploadWeb(id, attachFileName, attachmentType, attachFile, description);
                resultMap = entity.convertToMap();
            } else if (attachmentType.getStoretype().equals(TapSystemConst.TapAttachmentStoreType.FastDFS)) {
                entity = this.uploadFastDFS(id, attachFileName, attachmentType, attachFile, description);
                resultMap = entity.convertToMap();
            }

            return (Map)resultMap;
        } catch (Exception var9) {
            throw new ServiceException(var9);
        }
    }

    /**
      * @author: shenyouyi
      * @date: 2020/6/16
      * @param
      * @description: 执行下载
      **/
    @Override
    public Map<String, Object> executeDownload(Map<String, Object> paraMap) {
        return cboAttachmentService.executeDownload(paraMap);
    }

    /**
      * @author: shenyouyi
      * @date: 2020/6/16
      * @param
      * @description: 删除文件
      **/
    @Override
    @Transactional
    public void deleteFile(String[] arrayId) {
        for (String id: arrayId) {
            PmAttachmentEntity entity = new PmAttachmentEntity();
            entity.setId(Long.valueOf(id));
            entity.setDisplayname(null);
            entity.setSavepath(null);
            entity.setFiletype(null);
            entity.setUploaddate(null);
            entity.setDescription(null);
            this.updateFields(entity, updateFields);
        }
    }

    /**
      * @author: shenyouyi
      * @date: 2020/6/16
      * @param
      * @description: 上传文件到Ftp服务器
      **/
    private PmAttachmentEntity uploadFtp(String id, String attachFileName, CboAttachmentTypeEntity attachmentType, File attachFile, String description) throws Exception {
        String tempDirectoryName = "";
        File tempDirectory = new File(tempDirectoryName);
        if (!tempDirectory.exists() && !tempDirectory.isDirectory()) {
            tempDirectory.mkdirs();
        }

        PmAttachmentEntity entity = new PmAttachmentEntity();
        entity.setId(Long.valueOf(id));
        entity.setDisplayname(attachFileName);
        entity.setAttachmenttypeid(attachmentType.getId());
        String ftpSavePath = (new SimpleDateFormat("yyyy/MM/dd")).format(new Date()) + "/";
        entity.setSavepath(ftpSavePath);
        entity.setFiletype(FileUtil.getExtention(attachFileName).toUpperCase());
        entity.setUploaddate(Calendar.getInstance().getTime());
        entity.setDescription(description);
        if (attachmentType.getCompresszip() == 2) {
            entity.setFilename(ConvertUtil.convertToString(id) + "." + entity.getFiletype());
            entity.setPwd("");
        } else {
            entity.setFilename(ConvertUtil.convertToString(id) + ".zip");
            String zippwd = "";
            if (attachmentType.getFtpencrypt() == 1) {
                zippwd = BaseUtil.getRandomString(8);
            }

            entity.setPwd(zippwd);
        }

        FileInputStream attachFileInputStream = null;

        try {
            attachFileInputStream = new FileInputStream(attachFile);
            double size = (double)attachFileInputStream.available();
            DecimalFormat df = new DecimalFormat("0.0");
            entity.setFilesize(df.format(size / 1024.0D) + "kb");
        } catch (Exception var28) {
            throw new ServiceException(var28);
        } finally {
            if (attachFileInputStream != null) {
                attachFileInputStream.close();
            }

        }

        this.updateFields(entity, updateFields);
        FTPProcessor ftpProcessor = null;

        try {
            ftpProcessor = new FTPProcessor();
            ftpProcessor.connect(attachmentType.getFtppath(), attachmentType.getFtpserver(), Integer.parseInt(attachmentType.getFtpport()), attachmentType.getFtpuser(), attachmentType.getFtppwd());
            File copyAttachFile = new File(tempDirectoryName + "/" + attachFileName);
            FileUtil.copyFile(attachFile, copyAttachFile);
            if (attachmentType.getCompresszip() == 2) {
                ftpProcessor.upload(tempDirectoryName + "/" + attachFileName, attachmentType.getFtppath(), ftpSavePath, entity.getFilename());
            } else {
                String zipFilePath = tempDirectoryName + "/" + entity.getFilename();
                ZipFile zipFile = new ZipFile(zipFilePath);
                ZipParameters parameters = new ZipParameters();
                parameters.setCompressionMethod(8);
                parameters.setCompressionLevel(5);
                if (!StringUtil.isEmpty(entity.getPwd())) {
                    parameters.setEncryptFiles(true);
                    parameters.setEncryptionMethod(0);
                    parameters.setPassword(entity.getPwd());
                }

                zipFile.addFile(copyAttachFile, parameters);
                ftpProcessor.upload(zipFilePath, attachmentType.getFtppath(), ftpSavePath, entity.getFilename());
            }
        } catch (Exception var27) {
            this.deleteById(ConvertUtil.convertToString(entity.getId()));
            throw new ServiceException(var27);
        } finally {
            FileUtil.deleteFile(tempDirectoryName + "/" + attachFileName);
            FileUtil.deleteFile(tempDirectoryName + "/" + entity.getFilename());
            FileUtil.deleteFile(tempDirectoryName);
            if (ftpProcessor != null) {
                ftpProcessor.close();
            }

        }

        return entity;
    }

    /**
      * @author: shenyouyi
      * @date: 2020/6/16
      * @param
      * @description: 上传文件到数据库
      **/
    public PmAttachmentEntity uploadDatabase(String id, String attachFileName, CboAttachmentTypeEntity attachmentType, File attachFile, String description) throws Exception {
        PmAttachmentEntity entity = new PmAttachmentEntity();
        entity.setId(Long.valueOf(id));
        entity.setDisplayname(attachFileName);
        entity.setAttachmenttypeid(attachmentType.getId());
        entity.setFilename(ConvertUtil.convertToString(id) + FileUtil.getExtention(attachFileName));
        entity.setFiletype(FileUtil.getExtention(attachFileName).toUpperCase());
        entity.setUploaddate(Calendar.getInstance().getTime());
        entity.setContent(FileUtil.convertFileToBytes(attachFile));
        entity.setSavepath("");
        entity.setPwd("");
        entity.setDescription(description);
        FileInputStream attachFileInputStream = null;

        try {
            attachFileInputStream = new FileInputStream(attachFile);
            double size = (double)attachFileInputStream.available();
            DecimalFormat df = new DecimalFormat("0.0");
            entity.setFilesize(df.format(size / 1024.0D) + "kb");
        } catch (Exception var16) {
            throw new ServiceException(var16);
        } finally {
            if (attachFileInputStream != null) {
                attachFileInputStream.close();
            }

        }

        this.updateFields(entity, updateFields);
        return entity;
    }

    /**
      * @author: shenyouyi
      * @date: 2020/6/16
      * @param
      * @description: 上传文件到服务器
      **/
    public PmAttachmentEntity uploadWeb(String id, String attachFileName, CboAttachmentTypeEntity attachmentType, File attachFile, String description) throws Exception {
        PmAttachmentEntity entity = new PmAttachmentEntity();
        String fileName = ConvertUtil.convertToString(id) + FileUtil.getExtention(attachFileName);
        entity.setId(Long.valueOf(id));
        entity.setSourcetype(attachmentType.getSourcetype());
        entity.setDisplayname(attachFileName);
        entity.setAttachmenttypeid(attachmentType.getId());
        entity.setFiletype(FileUtil.getExtention(attachFileName).toUpperCase());
        entity.setUploaddate(Calendar.getInstance().getTime());
        entity.setFilename(fileName);
        entity.setDescription(description);
        FileInputStream attachFileInputStream = null;

        try {
            attachFileInputStream = new FileInputStream(attachFile);
            double size = (double)attachFileInputStream.available();
            DecimalFormat df = new DecimalFormat("0.0");
            entity.setFilesize(df.format(size / 1024.0D) + "kb");
        } catch (Exception var33) {
            throw new ServiceException(var33);
        } finally {
            if (attachFileInputStream != null) {
                attachFileInputStream.close();
            }

        }

        String savePath = "attached/" + attachmentType.getSourcetype() + "/" + (new SimpleDateFormat("yyyy/MM/dd")).format(new Date()) + "/";
        entity.setSavepath(savePath);
        String serverSavePath = BaseUtil.getProjectPath() + savePath;
        File serverSaveFile = new File(serverSavePath);
        if (!serverSaveFile.exists()) {
            serverSaveFile.mkdirs();
        }

        FileOutputStream fos = new FileOutputStream(serverSavePath + fileName);
        byte[] buffer = new byte[1024];
        FileInputStream in = new FileInputStream(attachFile);

        try {
            boolean var17 = false;

            int num;
            while((num = in.read(buffer)) > 0) {
                fos.write(buffer, 0, num);
            }
        } catch (Exception var35) {
            var35.printStackTrace(System.err);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }

                if (fos != null) {
                    fos.close();
                }
            } catch (IOException var32) {
            }

        }

        this.updateFields(entity, updateFields);
        return entity;
    }

    /**
      * @author: shenyouyi
      * @date: 2020/6/16
      * @param
      * @description: 上传文件到FastDfs服务器
      **/
    public PmAttachmentEntity uploadFastDFS(String id, String attachFileName, CboAttachmentTypeEntity attachmentType, File attachFile, String description) throws Exception {
        String fileUrl = fastDFSClient.uploadFile(attachFile);
        PmAttachmentEntity entity = new PmAttachmentEntity();
        entity.setId(Long.valueOf(id));
        entity.setSourcetype(attachmentType.getSourcetype());
        entity.setDisplayname(attachFileName);
        entity.setAttachmenttypeid(attachmentType.getId());
        entity.setSavepath(fileUrl);
        entity.setFilename(attachFileName);
        entity.setPwd("");
        entity.setFiletype(FileUtil.getExtention(attachFileName).toUpperCase());
        entity.setUploaddate(Calendar.getInstance().getTime());
        entity.setDescription(description);
        FileInputStream attachFileInputStream = null;

        try {
            attachFileInputStream = new FileInputStream(attachFile);
            double size = (double)attachFileInputStream.available();
            DecimalFormat df = new DecimalFormat("0.0");
            entity.setFilesize(df.format(size / 1024.0D) + "kb");
            this.updateFields(entity, updateFields);
        } catch (Exception var17) {
            this.fastDFSClient.deleteFile(fileUrl);
        } finally {
            if (attachFileInputStream != null) {
                attachFileInputStream.close();
            }

        }

        return entity;
    }

}
